import React, { Component } from 'react'
import { getMusicInfo, getMusicUrl } from "../api/test"
import {Link} from "react-router-dom"
import styles from "./about.less"
import { connect } from "react-redux"
import { searchQuery } from './../utils/querySearch';
@connect(
  (state) => ({
    PayingMusic: state.PayingMusic,
  }),
  dispatch => ({
    setMusic: (info)=>dispatch({type: 'platingMusic/save', payload:info}),
    addMusicList: (info)=>dispatch({type: 'musicList/add', payload:{info}}),
  })
)
export default class About extends Component {
  state = {
    dataList: [],
  }
  componentDidMount() {
    let search = this.props.location.search
    const {keyword} = searchQuery(search)
    if(keyword) {
      this.setState({
        keywords: keyword
      },() => {
        this.searchKeywords()
      })
    }
  }
  componentDidUpdate(oldVal) {
    let newSearch = this.props.location.search || ""
    let oldSearch = oldVal.location.search || ""
    const {keyword: newKey = null} = searchQuery(newSearch)
    const {keyword: oldKey = null} = searchQuery(oldSearch)
    if(newKey !== oldKey && newKey) {
        this.setState({
          keywords: newKey
        },() => {
          this.searchKeywords()
        })
    }

  }
  searchKeywords = async () => {
    let res = await getMusicInfo({keywords: this.state.keywords})
    console.log(res);
    this.setState({
      dataList: res.songs
    })
  }
  openMusic =async(detail) => {
    
      this.props.setMusic(detail)
  }
  addMusicList = async (detail) => {
    if(!this.props.PayingMusic.id) {
      this.openMusic(detail)
    }
    this.props.addMusicList(detail)
  }
  render() {
    const { dataList} = this.state
    return (
      <div>
        {dataList.map(item => (
          <div key={item.id}>
            <div>歌曲名： {item.name}</div>
            <div>艺术家： {
              item.artists.map((artists, index) => (
                <span key={index}>{artists.name} |</span>
              ))
            }</div>
            <div>专辑：{item.album.name}</div>
            <button className={styles.open_btn} onClick={() => this.openMusic(item)}>点击播放</button>
            <button className={styles.open_btn} onClick={() => this.addMusicList(item)}>加入播放列表</button>
            <hr/>
          </div>
        ))}
      </div>
    )
  }
}
